package com.piggy.common.satoken.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.piggy.common.core.exception.base.BaseException;
import com.piggy.common.satoken.constants.SaTokenConst;
import com.piggy.common.satoken.helper.LoginHelper;
import com.piggy.system.api.model.LoginUser;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Objects;

public class TokenEndpointInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = extractHeaderToken(request);
        if (StrUtil.isBlank(token)) {
            return true;
        }

        if (StrUtil.isNotBlank(token) && token.equals("undefined")) {
            throw new BaseException("系统登录异常，请重新登录");
        }

        LoginUser loginUser = LoginHelper.getLoginUser(token);
        if (ObjectUtil.isNull(LoginHelper.getLoginUser())) {
            LoginHelper.storage(loginUser);
            return true;
        }
        if (!(Objects.equals(LoginHelper.getLoginUser().getUserId(), loginUser.getUserId()))) {
            LoginHelper.storage(loginUser);
        }

        return true;
    }

    /**
     * Extract the OAuth bearer token from a header.
     *
     * @param request The request.
     * @return The token, or null if no OAuth authorization header was supplied.
     */
    protected String extractHeaderToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders(SaTokenConst.AUTHORIZATION);
        while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
            String value = headers.nextElement();
            if ((value.toLowerCase().startsWith(SaTokenConst.BEARER.toLowerCase()))) {
                String authHeaderValue = value.substring(SaTokenConst.BEARER.length()).trim();
                // Add this here for the auth details later. Would be better to change the signature of this method.
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }

        return null;
    }

}
